package com.power.sifa.approve.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
import com.plf.common.domain.PageDataResponse;
import com.plf.common.domain.YesNo;
import com.plf.common.exception.BusinessException;
import com.plf.common.utils.StringUtil;
import com.plf.core.base.model.EnumerationHelper;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.approve.dao.Apl_admre_auditDao;
import com.power.sifa.approve.dao.Apl_admreviewDao;
import com.power.sifa.approve.model.*;
import com.power.sifa.approve.model.enumeration.*;
import com.power.sifa.approve.model.pageInfo.Apl_admreviewPageInfo;
import com.power.sifa.approve.model.pojo.vo.AdmireTargetVO;
import com.power.sifa.approve.service.Apl_admreviewService;
import com.power.sifa.approve.service.Apl_checkdocService;
import com.power.sifa.approve.service.Apl_limit_replyService;
import com.power.sifa.approve.service.Apl_targetService;
import com.power.sifa.statistics.model.pageInfo.StatisticsInfo;
import com.power.sifa.std.model.Std_admunit;
import com.power.sifa.std.service.Std_admunitService;
import com.power.sifa.util.CnwordUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 行政复议申请业务层实现
 */
@Service
@Slf4j
public class Apl_admreviewServiceImpl extends BaseServiceImpl implements Apl_admreviewService {

    private final Double LOWESTRATE = 30.00;

    @Resource
    private Apl_targetService apl_targetService;
    @Resource
    private Std_admunitService std_admunitService;
    @Resource
    private Apl_admreviewDao dao;
    @Resource
    private Apl_limit_replyService apl_limit_replyService;
    @Resource
    private Apl_admre_auditDao apl_admre_auditDao;
    @Resource
    private EnumerationHelper helper;

    @Resource
    private Apl_checkdocService apl_checkdocService;

    public Apl_admreviewServiceImpl(Apl_targetService apl_targetService, Std_admunitService std_admunitService, Apl_admreviewDao dao, Apl_limit_replyService apl_limit_replyService) {
        this.apl_targetService = apl_targetService;
        this.std_admunitService = std_admunitService;
        this.dao = dao;
        this.apl_limit_replyService = apl_limit_replyService;
    }

    @Override
    public Apl_admreview getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Apl_admreview apl_admreview) {
        // save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (apl_admreview.getPrimaryKey() != null) {
            Apl_admreview apl_admreviewfDb = dao.findById(apl_admreview.getPrimaryKey()).orElse(null);
            if (apl_admreviewfDb != null) {
                BeanUtils.copyProperties(apl_admreview, apl_admreviewfDb);
                dao.save(apl_admreviewfDb);
                return;
            }
        }
        dao.save(apl_admreview);
    }

    @Override
    public void removeById(Serializable id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Apl_admreview> findAll(Apl_admreviewPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if ("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        } else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber() <= 1 ? 0 : pageInfo.getPageNumber() - 1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<Integer> ids) {
        dao.removeByIds(ids);
    }

    @Override
    public List<Apl_admreview> findAll() {
        return dao.findAll();
    }

    @Override
    public void saveAll(List<Apl_admreview> list) {
        dao.saveAll(list);
    }


    /**
     * 根据传入条件查询行政复议申请联合主表的分页结果
     */
    @Override
    public PageDataResponse findJoinAll(Apl_admreviewPageInfo pageinfo) {
        List<Apl_admreview> list = this.dao.findList(pageinfo);
        // 分页
        PageDataResponse page = new PageDataResponse();
        if (CollectionUtil.isNotEmpty(list)) {
//            for (Apl_admreview data : list) {
//                data.geneText();
//            }
            Long total = Long.valueOf(pageinfo.getAllcount());
            int size = pageinfo.getPageSize() * pageinfo.getPageNumber();
            if (total.intValue() - size > 0) {
                page.setNextPage(pageinfo.getPageNumber() + 1);
            }
            page.setSize(pageinfo.getPageSize());
            page.setCurrent(pageinfo.getPageNumber());
            page.setTotal(total);
        } else {
            page.setSize(0);
            page.setCurrent(1);
            page.setTotal(0L);
        }
        page.setRecords(list);
        return page;
    }

    /**
     * 行政复议联-根据相似度查询对应的相似行政复议申请
     *
     * @param applyId
     * @return
     */
    @Override
    public List<Apl_admreview_similarity> getSimilarityReview(String applyId) {
        // 拿取当条数据
        Apl_admreview mainReviewData = this.dao.findById(applyId).orElse(null);
        if (ObjectUtil.isNotNull(mainReviewData)) {
            // 基准案由
            String compareMainText = StringUtils.isNotEmpty(mainReviewData.getReason()) ? mainReviewData.getReason() : "";
            // 查询和该次申请相同的申请人的在执行中的流程的数据
            List<Map<String, Object>> queryResult = this.dao.getSimilarityReview(applyId);
            List<Apl_admreview_similarity> similarityList = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(queryResult)) {
                if (CollectionUtil.isNotEmpty(queryResult)) {
                    similarityList = JSON.parseArray(JSON.toJSONString(queryResult), Apl_admreview_similarity.class);
                }
                Apl_admreview_similarity mainData = similarityList.stream().filter(item -> item.getApplyid().equals(applyId)).findFirst().orElse(null);
                similarityList = similarityList.stream().filter(item -> !item.getApplyid().equals(applyId)).collect(Collectors.toList());
                // 执行相似度算法 拿取对应相似度的数据
                similarityList.forEach(item -> {
                    // 当前案由都为空
                    if (StringUtils.isEmpty(compareMainText) && StringUtils.isEmpty(item.getReason())) {
                        item.setSimilarityRate(100.00);
                    } else {
                        BigDecimal similarity = BigDecimal.valueOf(CnwordUtil.findSimilarity(item.getReason(), compareMainText) * 100);
                        double formate_similarity = similarity.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        item.setSimilarityRate(formate_similarity);
                    }
                });
//                similarityList = similarityList.stream().filter(item -> NumberUtil.compare(item.getSimilarityRate(),
//                        LOWESTRATE) > 0).sorted(Comparator.comparing(Apl_admreview_similarity::getSimilarityRate).reversed()).collect(Collectors.toList());

                similarityList = similarityList.stream().sorted(Comparator.comparing(Apl_admreview_similarity::getSimilarityRate).reversed()).collect(Collectors.toList());
                if (ObjectUtil.isNotNull(mainData)) {
                    similarityList.add(0, mainData);
                }
                return similarityList;
            }
        }
        return Collections.emptyList();
    }

    @Override
    public void updateStatus(String id, Integer status) {
        this.dao.updateStatus(id, status);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTargetName(String applyid, String targetname, String targetadid, Map<String,Apl_target> targetInfo) throws BusinessException {
        // 更新行政复议表，
        Apl_admreview apl_admreview = this.getById(applyid);
        // 若当前applyid数据没有入库 ，只做页面保存，等页面点击提交后再通过流程统一保存
        if (ObjectUtil.isNotNull(apl_admreview)) {
            apl_admreview.setTargetname(targetname);
            apl_admreview.setTargetadid(targetadid);
            this.saveOrUpdate(apl_admreview);
            // 查询全部的行政单位
            List<String> adids = Arrays.asList(targetadid.split(","));
            List<Std_admunit> unitList = std_admunitService.getUnitByIds(adids);
            if (CollectionUtil.isNotEmpty(unitList)) {
                // 更新被申请人表
                apl_targetService.removeByApplyid(applyid);
                List<Apl_target> targets = unitList.stream().map(unit -> Apl_target.builder().id(NanoIdUtils.randomNanoId())
                        .applyid(applyid).name(unit.getName()).adid(unit.getAdid()).admunitid(unit.getId())
                        .manager(ObjectUtil.isNotNull(targetInfo.get(unit.getId())) ? targetInfo.get(unit.getId()).getManager(): null).
                        agenter(ObjectUtil.isNotNull(targetInfo.get(unit.getId())) ? targetInfo.get(unit.getId()).getAgenter(): null).
                        address(ObjectUtil.isNotNull(targetInfo.get(unit.getId())) ? targetInfo.get(unit.getId()).getAddress(): null).
                        phone(ObjectUtil.isNotNull(targetInfo.get(unit.getId())) ? targetInfo.get(unit.getId()).getPhone(): null).build()).collect(Collectors.toList());
                apl_targetService.saveAll(targets);
            } else {
                throw new BusinessException("组织机构对应查询为空");
            }
        }
    }

    @Override
    public void updatesSonStatus(String id, String sonstatus) {
        this.dao.updatesSonStatus(id, sonstatus);
    }

    /**
     * 更新被申请人是否答复字段和答复时限
     *
     * @param applyid
     * @param reply
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTargetReply(String applyid, Boolean reply) {
        // 1. 更新主流程答复状态和答复时限
        Apl_limit_reply apl_limit_reply = apl_limit_replyService.getById(applyid);
        if (ObjectUtil.isNotNull(apl_limit_reply)) {
            apl_limit_reply.setReplydate(new Date());
            apl_limit_replyService.saveOrUpdate(apl_limit_reply);
        }
        Apl_admreview apl_admreview = this.getById(applyid);
        if (ObjectUtil.isNotNull(apl_admreview)) {
            apl_admreview.setIstargetreply(reply ? YesNo.YES : YesNo.NO);
            this.saveOrUpdate(apl_admreview);
        }
        // 2. 更新子流程的答复状态和答复时限
        this.apl_admre_auditDao.updateIstargetreply(applyid, YesNo.YES);

    }

    /**
     * 获取对应的行政复议子状态
     *
     * @param applyid
     * @return
     */
    @Override
    public List<String> getSonStatusByIds(String applyid) {
        Apl_admreview apl_admreview = this.getById(applyid);
        if (ObjectUtil.isNotNull(apl_admreview) && StringUtils.isNotEmpty(apl_admreview.getSonstatus())) {
            return Arrays.stream(apl_admreview.getSonstatus().split(",")).distinct().map(item ->
                    ObjectUtil.isNotNull(Tp_proctypeEnum.getByStatus(Integer.parseInt(item))) ?
                            Tp_proctypeEnum.getByStatus(Integer.parseInt(item)).getKey() : null).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    @Override
    public void updatesDecisiontype(String id, Integer decisiontype, Integer childId, String childName) {
        this.dao.updatesDecisiontype(id, decisiontype, childId, childName);
    }


    @Override
    public PageDataResponse queryArchivePage(Apl_admreviewPageInfo pageInfo) {
        List<Apl_admreview> list = this.dao.queryArchiveData(pageInfo);
        // 分页
        PageDataResponse page = new PageDataResponse();
        if (CollectionUtil.isNotEmpty(list)) {
            for (Apl_admreview data : list) {
                data.geneText();
            }
            Long total = Long.valueOf(pageInfo.getAllcount());
            int size = pageInfo.getPageSize() * pageInfo.getPageNumber();
            if (total.intValue() - size > 0) {
                page.setNextPage(pageInfo.getPageNumber() + 1);
            }
            page.setSize(pageInfo.getPageSize());
            page.setCurrent(pageInfo.getPageNumber());
            page.setTotal(total);
        } else {
            page.setSize(0);
            page.setCurrent(1);
            page.setTotal(0L);
        }
        page.setRecords(list);
        return page;
    }

    @Override
    public void updatesAcceptExamineUsers(String id, String firstuserid, String firstusername, String seconduserid, String secondusername) {
        this.dao.updatesAcceptExamineUsers(id, firstuserid, firstusername, seconduserid, secondusername);
    }

    @Override
    public void updatesHearExamineUsers(String id, String firstuserid, String firstusername, String seconduserid, String secondusername) {
        this.dao.updatesHearExamineUsers(id, firstuserid, firstusername, seconduserid, secondusername);
    }

    /**
     * 通过applyic查询申请人信息
     *
     * @param applyid
     * @return
     */
    @Override
    public AdmireTargetVO getAdmreviewInfoAndCheckDoc(String applyid) {
        // 查询行政复议申请记录
        Apl_admreview apl_admreview = this.getById(applyid);
        // apl_admreview.geneText();
        // 被申请人
        List<Apl_target> targetList = this.apl_targetService.getTargetListByApplyid(applyid);
        // 相关规范性文件
        List<Apl_checkdoc> checkDocList = this.apl_checkdocService.getByApplyid(applyid);
        return AdmireTargetVO.builder().admreview(apl_admreview).targetList(targetList)
                .checkDocList(checkDocList).build();
    }

    @Override
    public String getReason(Integer prtype) {
        if (null == prtype) {
            return "行政不作为";
        }
        return helper.getDescription(prtype);
    }

    @Override
    public String getAdmreReason(Apl_admreview admreObj) {
        StringBuffer reason = new StringBuffer();
        // 不履行法定职责
        if (YesNo.YES == admreObj.getIsomission()) {
            reason.append("申请人对被申请人不履行法定职责不服，向市政府申请行政复议，提出");
            reason.append(this.spellRequestStr(admreObj.getOmrequest()));
            if (!StringUtil.isEmpty(admreObj.getAdmrequest())) {
                reason.append("说明如下：" + admreObj.getAdmrequest());
            }
        } else {
            if (null == admreObj.getPrrequest()) {
                log.error("getAdmreReason 行政复议请求（行政作为）不能为空");
                throw new RuntimeException("行政复议请求（行政作为）不能为空");
            }
            if (Tp_admpr.OTHER.getKey() == admreObj.getPrtype()) {
                // 其它行政行为
                reason.append("申请人不服被申请人作出的");
                reason.append(admreObj.getPrname());
                reason.append("，向市政府申请行政复议，提出");
                reason.append(this.spellRequestStr(admreObj.getPrrequest()));
                if (!StringUtil.isEmpty(admreObj.getAdmrequest())) {
                    reason.append("说明如下：" + admreObj.getAdmrequest());
                }
            } else {
                // 具体行政行为
                reason.append("申请人不服被申请人作出的");
                reason.append(helper.getDescription(admreObj.getPrtype()));
                if (!StringUtil.isEmpty(admreObj.getPrcode())) {
                    reason.append("（编号：" + admreObj.getPrcode() + "）");
                }
                reason.append("，向市政府申请行政复议，提出");
                reason.append(this.spellRequestStr(admreObj.getPrrequest()));
                if (!StringUtil.isEmpty(admreObj.getAdmrequest())) {
                    reason.append("说明如下：" + admreObj.getAdmrequest());
                }
            }
        }
        return reason.append("。").toString();
    }

    /**
     * 拼接请求文本
     *
     * @param enumStr
     * @return
     */
    private String spellRequestStr(String enumStr) {
        StringBuffer str = new StringBuffer();
        String[] reqEnums = enumStr.split(",");
        int i = 0;
        for (String enumId : reqEnums) {
            str.append(helper.getDescription(Integer.valueOf(enumId)));
            if (i != 0 && i != reqEnums.length - 1) {
                str.append("、");
            }
            i++;
        }
        return str.append("请求").toString();
    }


    /**
     * 查询全部完结的行政复议申请
     */
    @Override
    public List<Apl_admreview> findAllEndedList() {
        return this.dao.findAllEndedList(St_apply.COMPLETELIST);
    }

    /**
     * 查询对应状态的行政复议数据
     */
    @Override
    public List<Apl_admreview> findAllReviewByStatus(List<String> status) {
        if (CollectionUtil.isNotEmpty(status)) {
            String statusStr = String.join(",", status);
            Apl_admreviewPageInfo pageInfo = new Apl_admreviewPageInfo();
            pageInfo.setF_status(statusStr);
            List<Apl_admreview> result = this.dao.findList(pageInfo);
            return result;
        }
        return this.dao.findAll();
    }


    @Override
    public void updateProctype(String id, Integer proctype) {
        this.dao.updateProctype(id, proctype);
    }

    @Override
    public void updateDecisiondate(String id, String decisiondate) {
        this.dao.updateDecisiondate(id, decisiondate);
    }

    /**
     * 大屏统计-统计审理中的状态
     *
     * @return
     */
    @Override
    public Long countPorcessingCaseStatus(StatisticsInfo info) {
//        StatisticsInfo info = StatisticsInfo.builder().acceptadid(acceptadid).status(Collections.singletonList(St_apply.ACCEPT)).build();
        info.setStatus(Collections.singletonList(St_apply.ACCEPT));
        return this.dao.countPorcessingCaseStatus(info);
    }

    /**
     * 大屏统计-统计已审结的状态
     *
     * @return
     */
    @Override
    public Long countEndedCaseStatus(String acceptadid) {
        StatisticsInfo info = StatisticsInfo.builder().acceptadid(acceptadid).status(St_apply.COMPLETELIST).build();
        return this.dao.countEndedCaseStatus(info);
    }

    /**
     * 大屏统计-统计中止状态的数据
     *
     * @return
     */
    @Override
    public Long countSuspendCaseStatus(String acceptadid) {
        StatisticsInfo info = StatisticsInfo.builder().acceptadid(acceptadid).status(Collections.singletonList(YesNo.YES)).build();
        return this.dao.countSuspendCaseStatus(info);
    }

    @Override
    public void updateQuedate(String id, String quedate) {
        this.dao.updateQuedate(id, quedate);
    }

    @Override
    public void updatesFirstUser(String id, String firstuserid, String firstusername) {
        this.dao.updatesFirstUser(id, firstuserid, firstusername);
    }

    @Override
    public void updatesSecondUser(String id, String seconduserid, String secondusername) {
        this.dao.updatesSecondUser(id,seconduserid, secondusername);
    }

    @Override
    public void updatesHearFirstUser(String id, String firstuserid, String firstusername) {
        this.dao.updatesHearFirstUser(id, firstuserid, firstusername);
    }

    @Override
    public void updatesHearSecondUser(String id, String seconduserid, String secondusername) {
        this.dao.updatesHearSecondUser(id, seconduserid, secondusername);
    }

    @Override
    public List<Apl_admreview> findAdmreviewList(List<String> ids) {
        return this.dao.findAdmreviewList(ids);
    }
}
